<template>
  <div class="flex flex-col h-full overflow-hidden">
    <app-header/>

    <main>
      <h2 class="page-title">{{ editMode ? '编辑用户' : '新增用户' }}</h2>

      <form @submit.prevent="saveUser" id="user-edit-add-form" class="config-form">
        <input type="hidden" v-if="editMode" id="user-id" v-model="userData.id">

        <div class="form-section">
          <h3 class="form-section-title">用户基本信息</h3>
          <div class="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-2">
            <div class="form-group">
              <label for="user-opid" class="form-label">工号/用户名 <span class="text-red-500">*</span></label>
              <input type="text" id="user-opid" v-model="userData.opid" class="form-input"
                     placeholder="输入用户工号或名称" :readonly="editMode" required>
              <p class="form-description" v-if="editMode">工号/用户名通常不能修改。</p>
            </div>
            <div class="form-group">
              <label for="user-name" class="form-label">姓名</label>
              <input type="text" id="user-name" v-model="userData.name" class="form-input"
                     placeholder="输入用户姓名 (可选)">
            </div>
            <div class="form-group col-span-2">
              <label for="user-password" class="form-label">密码 <span v-if="!editMode"
                                                                       class="text-red-500">*</span></label>
              <input type="password" id="user-password" v-model="password" class="form-input" placeholder="设置用户密码"
                     :required="!editMode">
              <p class="form-description" v-if="editMode">留空则不修改密码。</p>
            </div>
          </div>
        </div>

        <div class="button-group">
          <button type="button" id="btn-cancel-user" class="hmi-button hmi-button-secondary" @click="goBack">
            <i class="fas fa-times"></i>取消
          </button>
          <button type="submit" id="btn-save-user" class="hmi-button hmi-button-primary" :disabled="isSaving">
            <i :class="isSaving ? 'fas fa-spinner fa-spin' : 'fas fa-save'"></i>{{
              isSaving ? '保存中...' : (editMode ? '保存修改' : '新增用户')
            }}
          </button>
        </div>
      </form>
    </main>

    <div v-if="notification.show" id="notification" class="notification"
         :class="{ 'notification-success': notification.type === 'success', 'notification-error': notification.type === 'error', 'show': notification.show }">
      <span id="notification-message">{{ notification.message }}</span>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

// 响应式数据
const userData = reactive({
  id: null,
  opid: '',
  name: '',
  role: 'user'
})

const password = ref('')
const isSaving = ref(false)

// 添加 notification 响应式对象
const notification = reactive({
  show: false,
  message: '',
  type: 'success'
})

// 编辑模式判断
const editMode = computed(() => route.params.id !== undefined && route.params.id !== '')

// 显示提示信息
const showNotification = (message, type = 'success') => {
  notification.show = true
  notification.message = message
  notification.type = type
  
  setTimeout(() => {
    notification.show = false
  }, 3000)
}

// 加载用户数据
const loadUserData = (userId) => {
  const users = userStore.get('users') || []
  const user = users.find(u => u.opid === userId)
  if (user) {
    userData.id = user.opid
    userData.opid = user.opid
    userData.name = user.name || ''
    userData.role = user.role || 'user'
  } else {
    showNotification('用户不存在', 'error')
    router.push('/settings/user-management')
  }
}

// 保存用户
const saveUser = async () => {
  try {
    isSaving.value = true
    const users = userStore.get('users') || []
    const dataToSave = { ...userData }

    if (editMode.value) {
      // 更新用户
      const userIndex = users.findIndex(u => u.opid === dataToSave.id)
      if (userIndex !== -1) {
        if (password.value) {
          dataToSave.password = password.value
        } else {
          dataToSave.password = users[userIndex].password
        }
        users[userIndex] = dataToSave
      }
    } else {
      // 新增用户
      dataToSave.password = password.value || '123456' // 默认密码
      users.push(dataToSave)
    }

    userStore.set('users', users)
    showNotification(`用户${editMode.value ? '更新' : '新增'}成功！`)
    
    // 立即返回上一页
    router.back()
  } catch (error) {
    showNotification('操作失败', 'error')
  } finally {
    isSaving.value = false
  }
}

// 返回列表页
const goBack = () => {
  router.back()
}

// 页面加载时初始化
onMounted(() => {
  if (editMode.value && route.params.id) {
    loadUserData(route.params.id)
  }
})

</script>

<style scoped>
/* --- Main Content Area --- */
main {
  flex-grow: 1;
  padding: 1.5rem;
  overflow-y: auto; /* Enable scrolling for form */
}

/* --- Configuration Form (Common Styles) --- */
.config-form {
  background-color: var(--bg-secondary);
  border-radius: 0.75rem;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -2px rgba(0, 0, 0, 0.05);
  padding: 1.5rem;
  border: 1px solid var(--border-color);
  max-width: 900px; /* Adjust max width for this form */
  margin: 0 auto; /* Center form */
}

.form-title {
  font-size: 1.1rem;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 1.5rem;
  text-align: center;
  border-bottom: 1px solid var(--border-color);
  padding-bottom: 0.75rem;
}

.form-section {
  margin-bottom: 1.5rem;
}

.form-section-title {
  font-size: 1rem;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 1rem;
}

.form-group {
  margin-bottom: 1rem;
}

.form-label {
  display: block;
  font-size: 0.875rem;
  font-weight: 500;
  color: var(--text-secondary);
  margin-bottom: 0.5rem;
}

.form-input {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid var(--border-color);
  border-radius: 0.375rem;
  font-size: 0.875rem;
  color: var(--text-primary);
  background-color: var(--bg-secondary);
}

.form-input:focus {
  outline: none;
  border-color: var(--accent-blue);
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.form-description {
  font-size: 0.75rem;
  color: var(--text-tertiary);
  margin-top: 0.25rem;
}

/* Button Styles */
.button-group {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 2rem;
}

.hmi-button {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  border-radius: 0.375rem;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.hmi-button i {
  font-size: 0.875rem;
}

.hmi-button-primary {
  background-color: var(--accent-blue);
  color: white;
  border: 1px solid transparent;
}

.hmi-button-primary:hover {
  background-color: #2563eb;
}

.hmi-button-secondary {
  background-color: var(--bg-secondary);
  color: var(--text-primary);
  border: 1px solid var(--border-color);
}

.hmi-button-secondary:hover {
  background-color: #f9fafb;
  border-color: #d1d5db;
}

.hmi-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* Notification Styles */
.notification {
  position: fixed;
  bottom: 1rem;
  left: 50%;
  transform: translateX(-50%);
  padding: 0.75rem 1.25rem;
  border-radius: 0.5rem;
  color: white;
  font-size: 0.875rem;
  font-weight: 500;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.3s ease, visibility 0.3s ease;
  z-index: 100;
}

.notification.show {
  opacity: 1;
  visibility: visible;
}

.notification-success {
  background-color: var(--status-green);
}

.notification-error {
  background-color: var(--status-red);
}

.page-title {
  font-size: 1.1rem;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 1.5rem;
  text-align: center;
}
</style>
